package com.zqh.forum.controller;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.config.AppConfig;
import com.zqh.forum.model.Message;
import com.zqh.forum.model.User;
import com.zqh.forum.services.IMessageService;
import com.zqh.forum.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@Tag(name = "站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IUserService userService;


    /**
     *
     * @param receiveUserId 接受者id
     * @param content 发送的信息
     */
    @PostMapping("/send")
    @Operation(summary = "发送站内信")
    @Parameters({
            @Parameter(name = "receiveUserId",description = "接受者id"),
            @Parameter(name = "content",description = "发送的信息")
    })
    private AppResult send(HttpServletRequest request,
                           @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                           @RequestParam("content") @NonNull String content){
        //获取用的session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //1.判断登录用户的当前的状态，禁言就报错，不可发站内信
        if(user.getState() == 1){
            //禁言状态
             return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.判断是否给自己发私信
        if(user.getId() == receiveUserId){
            //给自己发私信
            return AppResult.failed("不可给自己发站内信");
        }
        //查找发送的用户信息
        User receiveUser = userService.selectById(receiveUserId);
        //3.校验接受者是否存在
        if(receiveUser == null || receiveUser.getDeleteState() == 1){
            //给自己发私信
            return AppResult.failed("接受者状态异常");
        }
        //4.封装要发送的对象
        Message message = new Message();
        message.setPostUserId(user.getId()); //发送者id
        message.setReceiveUserId(receiveUserId); //接受者id
        message.setContent(content); //发送信息
        message.setUpdateTime(new Date());
        //5.调用services
        messageService.create(message);
        //返回结果
        return AppResult.success("发送成功");
    }

    /**
     * 获取未读消息个数
     * @param request 从session中获取当前用户的id
     * @return 未读的站内信个数
     */
    @Operation(summary = "获取未读站内信的消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用services层
        Integer count = messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(count);
    }

    /**
     * 查询用户的所有站内信
     */
    @GetMapping("/getAll")
    @Operation(summary = "查看用户所有的站内信")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用services层
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }

    /**
     * @param id 站内信id
     */
    @Operation(summary = "将站内信状态设置为已读")
    @PostMapping("/markRead")
    @Parameter(name = "id", description = "站内信id")
    public AppResult markRead(HttpServletRequest request,
                              @RequestParam("id") @NonNull Long id){
        //1.根据站内信id查询站内信的详情信息
        Message message = messageService.selectById(id);
        if(message == null || message.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //2.站内信是否是当前用户发送
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否是自己
        if(!user.getId().equals(message.getReceiveUserId())){
            //自己发送
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //3.调用services
        messageService.updateStateById(id, (byte) 1);
        //返回结果
        return AppResult.success();
    }

    /**
     * 站内信的回复
     * @param repliedId 站内信的id(要回复的站内信id)
     * @param content 回复的内容
     * @return 返回回复的结果集
     */
    @Operation(summary = "站内信的回复")
    @PostMapping("/reply")
    @Parameters({
            @Parameter(name = "repliedId", description = "站内信的id"),
            @Parameter(name = "content", description = "回复的内容")
    })
    public AppResult<Message> reply(HttpServletRequest request,
                                    @RequestParam("repliedId") @NonNull Long repliedId,
                                    @RequestParam("content") @NonNull String content){
        //获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验当前登录用户的状态是否被禁言
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //校验站内信是否存在
        Message existsMessage = messageService.selectById(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() == 1){
            //站内信不存在
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        //判断是否给自己回复信息
        if(user.getId() == existsMessage.getPostUserId()){
            //不能给自己回复
            return AppResult.failed("不能给自己站内信回复信息");
        }

        //构造要回复的内容信息集合
        Message message = new Message();
        message.setReceiveUserId(existsMessage.getPostUserId()); //接受者
        message.setPostUserId(user.getId()); //发送者
        message.setContent(content); //内容

        //调用service层
        messageService.reply(repliedId,message);
        //返回结果
        return AppResult.success();
    }



}
